﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace DownloadWebFile
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                string[] webnames = args;
                DownloadWebFile.Program prog = new Program();
                prog.Download(webnames);
            }
        }

        private void WriteErrorText(Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("错误:消息:" + e.Message + ",调用堆栈:" + e.StackTrace + ",错误编码" + e.HResult);
            Console.ForegroundColor = ConsoleColor.Green;
        }

        private void Download(string[] webname)
        {
            WebClient web = new WebClient();
            web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
            System.IO.FileStream fs;
#if DEBUG
            Console.WriteLine(webname[webname.Length - 2]);
#endif
            for (int i = 1; i < webname.Length-1; i++)
            {
                fs = new System.IO.FileStream(webname[webname.Length - 2], System.IO.FileMode.OpenOrCreate);
                Console.ForegroundColor = ConsoleColor.Green;
                try
                {
                    if(webname[2] == "DefText")
                    {
                        byte[] bytes = web.DownloadData(webname[0]);
                        fs.Write(bytes, 0, bytes.Length);
                    }
                    else if(webname[2] == "Datas")
                    {
                        byte[] bytes = web.DownloadData(webname[0]);
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
                catch(Exception e)
                {
                    WriteErrorText(e);
                }
                finally
                {
                    fs.Close();
                    web.Dispose();
                }
                Console.WriteLine("第" + i + "个(" + i + "/" + (webname.Length - 2).ToString() + ")");
            }
        }
    }
}
